package com.meida.module.arc.provider.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.meida.common.base.utils.FlymeUtils;
import com.meida.common.utils.ApiAssert;
import com.meida.module.arc.client.entity.ArcCompilationRef;
import com.meida.module.arc.provider.mapper.ArcCompilationRefMapper;
import com.meida.module.arc.provider.service.ArcCompilationRefService;
import com.meida.common.mybatis.base.service.impl.BaseServiceImpl;
import com.meida.common.mybatis.model.ResultBody;
import org.springframework.stereotype.Service;
import com.meida.common.base.entity.EntityMap;
import com.meida.common.mybatis.query.CriteriaQuery;
import org.springframework.transaction.annotation.Propagation;
import com.meida.common.mybatis.query.CriteriaSave;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 编研素材关联接口实现类
 *
 * @author flyme
 * @date 2022-01-04
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class ArcCompilationRefServiceImpl extends BaseServiceImpl<ArcCompilationRefMapper, ArcCompilationRef> implements ArcCompilationRefService {

    @Override
    public ResultBody beforeAdd(CriteriaSave cs, ArcCompilationRef acr, EntityMap extra) {
        return ResultBody.ok();
    }



    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public ResultBody beforePageList(CriteriaQuery<ArcCompilationRef> cq, ArcCompilationRef acr, EntityMap requestMap) {
      cq.orderByDesc("acr.createTime");
      return ResultBody.ok();
    }

    @Override
    public void addCompilationRef(Long compilationId, Long categoryId, List<Long> arcInfoIds) {
        arcInfoIds.forEach(item->{
            CriteriaQuery<ArcCompilationRef> query = new CriteriaQuery<ArcCompilationRef>(ArcCompilationRef.class);
            query.lambda().eq(ArcCompilationRef::getArcInfoId,item).eq(ArcCompilationRef::getCompilationId,compilationId);
            Long count = count(query);
            if(FlymeUtils.isEmpty(count)||count==0){
                ArcCompilationRef ref = new ArcCompilationRef();
                ref.setArcInfoId(item);
                ref.setCategoryId(categoryId);
                ref.setCompilationId(compilationId);
                this.save(ref);
            }
        });
    }

    @Override
    public void removeCompilation(List<Long> arcInfoIds) {
        LambdaQueryWrapper<ArcCompilationRef> query = new LambdaQueryWrapper<>();
        query.in(ArcCompilationRef::getArcInfoId,arcInfoIds);
        this.remove(query);
    }
}
